<?php

/**
 * This is the model class for table "{{content}}".
 *
 * The followings are the available columns in table '{{content}}':
 * @property integer $id
 * @property integer $category_id
 * @property string $type
 * @property string $title
 * @property string $sub_title
 * @property string $slug
 * @property string $description
 * @property string $content
 * @property string $serial
 * @property string $author
 * @property string $meta_keyword
 * @property string $meta_description
 * @property string $meta_robots
 * @property string $meta_revisit_after
 * @property string $image
 * @property string $status
 * @property integer $num_views
 * @property string $publishing_start
 * @property string $publishing_end
 * @property string $created_date
 * @property integer $created_user_id
 * @property string $updated_date
 * @property integer $updated_user_id
 * @property integer $activate_user_id
 * @property string $activate_date
 * @property integer $allow_comment
 * @property integer $num_comments
 * @property integer $is_hot
 * @property integer $ordering
 * @property integer $sticky
 * @property string $language
 */
class Content extends CActiveRecord
{
    public $multi_categories;
    public $publishing_start_time;
    public $publishing_end_time;
    public $activate_date_range;
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return Content the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{content}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
            array('title,slug,type,category_id','required'),
            array('title,slug','unique'),
			array('category_id, num_views, created_user_id, updated_user_id, activate_user_id, serial, allow_comment, num_comments, is_hot, ordering, sticky', 'numerical', 'integerOnly'=>true),
			array('type, title, sub_title, slug, author, meta_keyword, meta_description, meta_robots, meta_revisit_after, image', 'length', 'max'=>255),
			array('status', 'length', 'max'=>8),
            array('image','fileOnServer','mime'=>array('image/png','image/jpeg','image/gif')),
            array('publishing_end','EdateCompare','compareAttribute'=>'publishing_start','operator'=>'>=', 'allowEmpty'=>true ,'dateFormat'=>Yii::app()->locale->getDateFormat('short')),
            //array('publishing_end','dateCompare','compareAttribute'=>'publishing_start','operator'=>'>', 'allowEmpty'=>true ,'format'=>'m/d/Y', 'message'=>'{attribute} '.t('must be greater than','Content'). ' "{compareValue}".'),
			array('language', 'length', 'max'=>10),
			array('description, content, created_date, updated_date, activate_date, multi_categories', 'safe'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, category_id, type, title, sub_title, slug, description, content, author, meta_keyword, meta_description, meta_robots, meta_revisit_after, image, status, num_views, created_date, created_user_id, updated_date, updated_user_id, activate_user_id, activate_date, allow_comment, num_comments, is_hot, ordering, sticky, language, activate_date_range', 'safe', 'on'=>'search'),
		);
	}
    /**
      * Add Behaviors
      */
    public function behaviors(){
        return array( 'EAdvancedArBehavior' => array(
            'class' => 'common.extensions.behaviors.ar.EAdvancedArBehavior'));
    }
	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
            'category'=>array(self::BELONGS_TO,'Category','category_id'),
            'userCreate'=>array(self::BELONGS_TO,'User','created_user_id'),
            'userUpdate'=>array(self::BELONGS_TO,'User','updated_user_id'),
            'userActive'=>array(self::BELONGS_TO,'User','activate_user_id'),
            'categories'=>array(self::MANY_MANY,'Category','{{content_category_assoc}}(content_id, category_id)'),
            'media'=>array(self::HAS_MANY,'ContentMedia','content_id'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => t('ID','content'),
			'category_id' => t('Category','content'),
			'type' => t('Type','content'),
			'title' => t('Title','content'),
			'sub_title' => t('Sub Title','content'),
			'slug' => t('Slug','content'),
			'description' => t('Description','content'),
			'content' => t('Content','content'),
			'author' =>  t('Author','content'),
			'meta_keyword' => t('Meta Keyword','content'),
			'meta_description' => t('Meta Description','content'),
			'meta_robots' => t('Meta Robots','content'),
			'meta_revisit_after' => t('Meta Revisit After','content'),
			'image' => t('Image','content'),
			'status' => t('Status','content'),
			'num_views' => t('Views','content'),
			'publishing_start' => t('Start Publishing Date','content'),
			'publishing_end' => t('Finish Publishing Date','content'),
			'publishing_start_time' => t('Start Publishing Time','content'),
			'publishing_end_time' => t('Finish Publishing Time','content'),
			'created_date' =>  t('Created Date','content'),
			'created_user_id' => t('Created User','content'),
			'updated_date' => t('Updated Date','content'),
			'updated_user_id' => t('Updated User','content'),
			'activate_user_id' => t('Activate User','content'),
			'activate_date' => t('Activate Date','content'),
			'allow_comment' => t('Allow Comment','content'),
			'num_comments' => t('Num Comments','content'),
			'is_hot' => t('Hot','content'),
			'ordering' => t('Ordering','content'),
			'sticky' => t('Sticky','content'),
			'language' => t('Language','content'),
			'serial' => t('Serial','content'),
			'multi_categories' => t('Other Categories','content'),
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('t.id',$this->id);
		$criteria->compare('category_id',$this->category_id);
		$criteria->compare('type',$this->type,true);
		$criteria->compare('t.title',$this->title,true);
		$criteria->compare('sub_title',$this->sub_title,true);
		$criteria->compare('slug',$this->slug,true);
		$criteria->compare('description',$this->description,true);
		$criteria->compare('content',$this->content,true);
		$criteria->compare('author',$this->author,true);
		$criteria->compare('meta_keyword',$this->meta_keyword,true);
		$criteria->compare('meta_description',$this->meta_description,true);
		$criteria->compare('meta_robots',$this->meta_robots,true);
		$criteria->compare('meta_revisit_after',$this->meta_revisit_after,true);
		$criteria->compare('image',$this->image,true);
		$criteria->compare('status',$this->status);
		$criteria->compare('num_views',$this->num_views);
		$criteria->compare('created_date',$this->created_date,true);
		$criteria->compare('created_user_id',$this->created_user_id);
		$criteria->compare('updated_date',$this->updated_date,true);
		$criteria->compare('updated_user_id',$this->updated_user_id);
		$criteria->compare('activate_user_id',$this->activate_user_id);
		$criteria->compare('activate_date',$this->activate_date,true);
		$criteria->compare('allow_comment',$this->allow_comment);
		$criteria->compare('num_comments',$this->num_comments);
		$criteria->compare('is_hot',$this->is_hot);
		$criteria->compare('ordering',$this->ordering);
		$criteria->compare('sticky',$this->sticky);
		$criteria->compare('language',$this->language,true);

        $criteria->compare('category.name',$this->filterCategory($this->category_id),true);
        if(isset($this->activate_date_range) && trim($this->activate_date_range) != '') {
            $active_date = explode(" - ",$this->activate_date_range);
            $date_start = convertTimeZone(date('Y-m-d H:i:s',CDateTimeParser::parse($active_date[0],app()->locale->getDateFormat('short'))),app()->timeZone);
            $date_end = convertTimeZone(date('Y-m-d H:i:s',CDateTimeParser::parse($active_date[1],app()->locale->getDateFormat('short'))),app()->timeZone);
            $criteria->addBetweenCondition('activate_date',$date_start,$date_end);
        }
        if($this->status != 'deleted') {
            $criteria->addCondition("status != 'deleted'");
        }
        $criteria->with = array('category');
        $dependency = new CDbCacheDependency('SELECT MAX(updated_date),MAX(created_date) FROM {{content}}');
		return new CActiveDataProvider(self::model()->cache(settings()->get('system','cache_time'),$dependency,2), array(
			'criteria'=>$criteria,
            'pagination'=>array(
                        'pageSize'=>settings()->get('general','site_page_size')
            ),
            'sort'=>array(
                'defaultOrder'=>'t.id DESC',
            ),
		));
	}
    public function beforeSave() {
        $current_user = getSession('current_user');
        if($this->getIsNewRecord()) {
            $this->created_date = new CDbExpression('UTC_TIMESTAMP()');
            $this->created_user_id = $current_user['id'];
            if ($_POST['Content']['publishing_start'] == '' || $_POST['Content']['publishing_start'] == null) {
               $this->publishing_start = new CDbExpression('UTC_TIMESTAMP()');
            }
        } else {
            $this->updated_date = new CDbExpression('UTC_TIMESTAMP()');
            $this->updated_user_id = $current_user['id'];
        }
        return parent::beforeSave();
    }
    public static function getOriginalSerial($id) {
        $content = Content::model()->findByPk($id);
        if(isset($content->serial)) {
         return self::getOriginalSerial($content->serial);
        } else {
            return $content->id;
        }
    }
    public function renderTitle($data,$row) {
        // $data ... the current row data
        // $row ... the row index
        return '<span rel="tooltip" data-original-title="'.t('Show details','content').'" style="color:#08c">'.ucfirst($data['title']).'</span><div style="color:#616161"><small> ( Slug :'.$data['slug'].' )</small></div>';
    }
    public function filterCategory($id){
        if(is_null($id)) return null;
        if($category = Category::model()->findByPk($id)) {
                return $category->name;
            } else return null;
    }
    public function actionRelational()
    {
        $id = Yii::app()->getRequest()->getParam('id');
        $model = Category::model()->findByPk($id);
        $this->renderPartial('_relational', array(
            'model'=>$model
        ));
    }
}